<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/14 0014
 * Time: 下午 3:35
 */
namespace App\Common;

use swoole_client as SwClient;
use EasySwoole\EasySwoole\ServerManager;
use App\Utility\BaseEnum;
use Swoole\Timer;

/**
 * TODO 使用WS方式创建数据库连接池；
 * TO 接受远程的SQL语句执行
 *
 * @author XCH
 */
class WSDBCommon
{

    protected static $instance = null;
    
    protected $client_uid = FALSE;
    protected $client_wsobj = FALSE;
    
    
    //单例模式
    public static function getInstance($unionkey)  {
        $allClients =  self::$instance;                 //单例对象使用KEY区别
        $oneObject = $allClients[$unionkey] ?? FALSE;   //连接对象值
        if(!($oneObject instanceof self)) {
            $oneObject = new self();
            $oneObject->setClientID($unionkey);         //创建主键
            $oneObject->setWebSocket(self::startServer());  //创建服务
            $allClients[$unionkey] = $oneObject;
            self::$instance = $allClients;
        }
        return $oneObject;
    }
    
    //唯一键
    public function __construct()    {
    }
    public function getClientID(){
        return $this->client_uid;
    }
    public function setClientID($client_id){
        $this->client_uid = $client_id;
    }
    
    //WS 服务对象
    public function getWebSocket(){
        return $this->client_wsobj;
    }
    
    //WS 设置服务
    public function setWebSocket($ws){
        $this->client_wsobj = $ws;
    }
    
    //WS 关闭服务
    public function closeWebSocket(){
        $this-> getWebSocket()-> close();
    }
    
    /**
     * TODO 执行指令发送
     * @param boolean $commond  命令行
     * @param boolean $recvFlag 是否要接收数据 默认为True
     * @return boolean string 查询结果数据
     */
    public function sendCommod($commond = FALSE, $recvFlag = TRUE,$loginFd=FALSE)
    {
        
        $clentObj = $this->getWebSocket();
        BaseEnum::Logger("ClientInfo:" . json_encode($clentObj),"user-login");
        $clentObj -> send($commond);        // 执行操作命令
        if ($recvFlag) {
            return FALSE;
        }
    }
    
    /**
     * TODO 接收消息 
     */
    public function getReceive($loginFd = FALSE){
        //$result = $this->getWebSocket() -> receive() ; // 接收数据并处理
        $conObj = $this->getWebSocket();
        $num = 0;
        while(true){
            BaseEnum::Logger("监听===>" .$loginFd,"user-login");
            $result = $conObj -> receive() ; // 接收数据并处理
            if($result && !empty($result)){
                BaseEnum::Logger("接收到异步WS消息===>" .$result,"user-login");
                if(!empty($loginFd) && intval($loginFd) > 0){
                    AuthCommon::pushFrontWeb($loginFd,$result);
                }
            }
            if($num>10)break;
            $num ++;
            sleep(1);
        }
    }
    
    
    /**
     * TODO 创建WS外部服务
     * @return object WS外部服务
     */
    public static function startServer()
    {
        /* if ($this->ssl)  { $type |= SWOOLE_SSL;  } */
        /* if ($this->ssl_key_file)  { $this->socket->set(array( 'ssl_key_file' => $this->ssl_key_file, 'ssl_cert_file' => $this->ssl_cert_file ));
        } */
        //$client = new \swoole_websocket_client(SWOOLE_SOCK_TCP,SWOOLE_SOCK_ASYNC); // new swoole_client(SWOOLE_TCP | SWOOLE_KEEP) ，这样就表示启用长连接。
        
        //$wssUrl = 'ws://dns.svnhai.com';
        $wssUrl = 'ws://push.games.com/online';
        $client = new \WebSocket\Client($wssUrl,["timeout"=> 60]);
        
        //$client->send($data);
        //$client = new \Swoole\Client\WebSocket('192.168.0.147:9501');
        
        //$client->on('connect',function($cli){
        //    echo 'Connect to Server Success';
        //});
        //$client ->on('receive',function($cli,$data){
        //BaseEnum::Logger("Client receive:" . json_encode($data),"user-login");
        /* $data = unjson_encode($data);
        switch($data[0]){
            case 'm':
                //消息转发
                foreach($data[1] as $fd){
                    $GLOBALS['ws']->push($fd,$data[2]);
                }
                break;
        } */
        //});
                
        /* $client->on('close',function($cli){
                echo 'Close to Server Success';
        });
                    
        $client->on('error',function($cli){
                    echo 'Error to Server Success';
        }); */
        //$client->connect('192.168.0.147',9501,5) or die("连接失败");
        return $client;
    }
    
    
}